package com.cmii.sjw.department.control.jsc.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cmii.sjw.department.control.jsc.config.SzcqrgzndzConfig;
import com.cmii.sjw.department.control.jsc.constant.StreamResponseHandler;
import com.cmii.sjw.department.control.jsc.service.BailianStreamAIService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jfh
 * @Date 2025年09月15日 15:39
 */
@Slf4j
@Service
public class BailianStreamAIServiceImpl implements BailianStreamAIService {

    @Autowired
    private StreamResponseHandler streamResponseHandler;

    @Autowired
    private SzcqrgzndzConfig szcqrgzndzConfig;

    /**
     * 调用百炼平台流式接口
     */
    public void callStreamAgent(SseEmitter emitter, String sessionId, String question) {
        Long recordId = null;

        try {
            // 创建问答记录
//            recordId = qaRecordService.createRecord(sessionId, question, modelId);

            // 构造请求参数
            JSONObject requestBody = new JSONObject()
                    .fluentPut("stream", "true")
                    .fluentPut("delta", "true")
                    .fluentPut("sessionId", sessionId)
                    .fluentPut("message", new JSONObject()
                            .fluentPut("text", question)
                            .fluentPut("metadata", new JSONObject())
                            .fluentPut("attachments", new JSONArray()));

            log.info("requestBody: {}", requestBody);

            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + szcqrgzndzConfig.getAppKey());
            headers.put("Content-Type", "application/json");
//            headers.put("Accept", "text/event-stream");

            // 发起流式请求
            HttpResponse response = HttpRequest.post(szcqrgzndzConfig.getUrl() + "/xlm-gateway-ftlzsf/sfm-api-gateway/gateway/agent/api/run")
                    .headerMap(headers, true)
                    .body(requestBody.toJSONString())
                    .execute();

            // 处理流式响应
            InputStream inputStream = response.bodyStream();
            String fullAnswer = streamResponseHandler.handleStreamResponse(recordId, inputStream, emitter);
            log.info("fullAnswer: {}", fullAnswer);
            // 完成记录
//            qaRecordService.completeRecord(recordId, fullAnswer);

            // 发送完成事件
//            emitter.send(SseEmitter.event().name("complete").data("done"));
            emitter.complete();

        }  catch (Exception e) {
            log.error("调用百炼平台流式接口失败", e);
//            if (recordId != null) {
//                qaRecordService.failRecord(recordId, e.getMessage());
//            }

            try {
                emitter.send(SseEmitter.event().name("error").data(e.getMessage()));
                emitter.complete();
            } catch (IOException ioException) {
                log.error("发送错误信息失败", ioException);
            }
        }
    }
}
